package edu.cuit.jead.mynetdisk.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.UrlResource;
import com.alibaba.fastjson.JSONObject;
import edu.cuit.jead.mynetdisk.common.Code;
import edu.cuit.jead.mynetdisk.common.Result;
import edu.cuit.jead.mynetdisk.entity.Fileinfo;
import edu.cuit.jead.mynetdisk.exception.AppException;
import edu.cuit.jead.mynetdisk.common.Result;
import edu.cuit.jead.mynetdisk.exception.AppException;
import edu.cuit.jead.mynetdisk.service.Fileservice;

import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Map;


/*
 *处理文件上传下载相关的接口
 */
@RestController
@RequestMapping("/files")
public class FileController {
    private String projectDir=System.getProperty("user.dir");
    private String datepath=projectDir.substring(0, projectDir.lastIndexOf("\\"));
    private String adress="\\files\\";

    private final Fileservice fileservice;

    public FileController(Fileservice fileservice) {
        this.fileservice = fileservice;
    }

    /**
     * 文件上传接口
     *
     */
    @PostMapping("/upload")
    public Result upload(@RequestPart("file") MultipartFile file,@RequestParam("email") String email) throws IOException {
        //找到文件的位置
        System.out.println("接口已调用");
        Fileinfo fileinfo = new Fileinfo();
        if (file.isEmpty()) {
            return Result.error(Code.FILE_NOT_EXIST);
        }
        String filePath = datepath+adress+email+"\\";
        System.out.println(filePath);
        if (!FileUtil.exist(filePath)) {//如果文件路径不存在就创建
            FileUtil.mkdir(filePath);
        }

        String fileName = file.getOriginalFilename();//文件的原始名称
        File savefile = new File(filePath + fileName);
        if(savefile.exists()){//如果当前上传文件已经存在
            throw new AppException(Code.FILE_EXIST);
        }

        Long size = file.getSize();// 获取文件大小
        Long usedspace=fileservice.getUsedSpace(email);
        Long totalspace=fileservice.getTotalSpace(email);
        if(size+usedspace>totalspace){
            throw new AppException(Code.SIZE_OUT);//如果超出总空间则报错
        }

        Integer id=fileservice.getID(email);
        fileinfo.setUserID(id);
        fileinfo.setEmail(email);
        fileinfo.setPath(filePath+fileName);
        if(id==null){
            return Result.error(500,"系统异常，请稍后再试");
        }
        fileinfo.setSize(size);
        System.out.println(fileinfo.getSize());
        Fileinfo result = fileservice.saveFile(fileinfo);
        if(result==null){
            return Result.error(500,"系统异常，请稍后再试");
        }
        //写入文件
        byte[] bytes =file.getBytes();
        FileUtil.writeBytes(bytes, filePath+fileName);
        String url= "http://localhost:5080/files/download/"+email+"/"+fileName;
        fileservice.updateUsedSpace(email,usedspace+size);


        return Result.success(url);
    }
    /**
     * 文件下载接口
     */
    @GetMapping("/download/{email}/{filename}")
    public Object download(@PathVariable String email,@PathVariable String filename, HttpServletResponse response) throws Exception {
        //找到文件的位置
        String filePath = datepath+adress+email+"/";//获取到当前项目的根路径
        String realPath = filePath+filename;
        if(!FileUtil.exist(realPath)){
            throw new AppException(Code.FILE_NOT_EXIST);
        }
        //读取文件的字节流
        byte[] bytes= FileUtil.readBytes(realPath);
        ServletOutputStream os= response.getOutputStream();
        //输出对象把文件写出到客户端
        os.write(bytes);//数组是一个字节数组，也就是文件的字节流数组
        os.flush();
        os.close();
        return new AppException(Code.DONWLOAD_SUCCESS);
    }

    @PostMapping("/move-to-trash")
    public Object moveToTrash(@RequestBody Map<String,String> params){
        String fileName=params.get("fileName");
        String email=params.get("email");
        String filePath = datepath + adress + email + "\\";
        File savefile = new File(filePath + fileName);
        if (!savefile.exists()) {//如果当前转移文件不存在
            throw new AppException(Code.FILE_NOT_EXIST);
        }
        Integer recycled = fileservice.getRecycled(filePath + fileName);
        if (recycled != 0) {
            throw new AppException(Code.FILE_EXIST);
        }

        Long filesize=fileservice.getSize(filePath + fileName);
        System.out.println(filePath+fileName);
        Long used_space=fileservice.getUsedSpace(email);
        fileservice.updateUsedSpace(email,used_space-filesize);
        recycled = 1;
        if (fileservice.updateRecycled(filePath + fileName, recycled) == 0)
            return Result.error(10008, "数据库修改失败");
        return Result.success("文件已放入回收站");
    }

    @PostMapping("/toggle-star")
    public Object star(@RequestBody Map<String,String> params){
        String fileName = params.get("fileName");
        String email = params.get("email");
        System.out.println(email);
        String filePath = datepath + adress + email + "\\";
        File savefile = new File(filePath + fileName);
        if (!savefile.exists()) {//如果当前转移文件不存在
            throw new AppException(Code.FILE_NOT_EXIST);
        }
        JSONObject result=new JSONObject();
        System.out.println(filePath+fileName);
        Integer colleted = fileservice.getCollected(filePath + fileName);
        if (colleted == 0) {
            colleted = 1;
            if (fileservice.updateCollect(filePath + fileName, colleted) == 0)
                return Result.error(10008, "数据库修改失败");
            result.put("isStarred",true);
        }
        else {
            colleted = 0;
            if (fileservice.updateCollect(filePath + fileName, colleted) == 0)
                return Result.error(10008, "数据库修改失败");
            result.put("isStarred",false);
        }
        result.put("id",4329);
        return result;
    }

    @PostMapping("/delete-permanently")
    public Result delete(@RequestBody Map<String,String> params) {
        String fileName = params.get("fileName");
        String email = params.get("email");
        String filePath = datepath + adress + email + "\\";
        File savefile = new File(filePath + fileName);
        System.out.println(filePath+fileName);
        if (!savefile.exists()) {//如果当前删除文件不存在
            throw new AppException(Code.FILE_NOT_EXIST);
        }
        if (savefile.delete()) {
            fileservice.deleteFile(filePath + fileName);
            return Result.success("文件已删除");
        } else
            return Result.error(10009, "文件未删除");
    }
}